package com.weme.common.util

import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.inputmethod.InputMethodManager
import com.weme.chat.bean.CallMessage
import com.weme.chat.bean.GiftMessage
import com.weme.chat.bean.toMap
import dev.kratos.api.user_server.v1.GiftInfo
import io.agora.CallBack
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.Conversation
import io.agora.chat.CustomMessageBody
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object AgoraClient {

    const val ACTION_TYPING_INPUT = "input"
    const val ACTION_TYPING_INPUT_END = "input_end"


    const val EVENT_TYPING_GIFT = "gift"//礼物消息
    const val EVENT_TYPING_CALL = "call"//im消息
  //  const val EVENT_TYPING_NO_RESPONSE = "noresponse"//未回复消息


    var agoraLogin = false

    private  var chatListenerManager= ChatListenerManager()

    // 单例实例
    private var instance: AgoraClient? = null

    fun getInstance(): AgoraClient {
        if (instance == null) {
            instance = AgoraClient
        }
        return instance!!
    }

    fun initialize() {
        // 在这里初始化 AgoraClient
    }

    fun loginToAgora(USERNAME: String, TOKEN: String, onConfirm: ((Boolean) -> Unit?)? = null) {
        if (TextUtils.isEmpty(USERNAME) || TextUtils.isEmpty(TOKEN)) {
           // UtilsApp.getTopActivity().showToast("Username or token is empty!")
            onConfirm?.invoke(false)
            return
        }
       // UserMKHelper.encode(UserMKHelper.UID,USERNAME)
        ChatClient.getInstance().loginWithAgoraToken(USERNAME, TOKEN, object : CallBack {
            override fun onSuccess() {
                agoraLogin = true
                ChatClient.getInstance().chatManager().loadAllConversations()
                Log.e("agora", "${USERNAME} Sign in agora success!")
                chatListenerManager.initListeners{
                    loginToAgora(USERNAME, TOKEN)
                }
                onConfirm?.invoke(true)
            }

            override fun onError(code: Int, error: String) {
                Log.e("agora", "name:${USERNAME}, token = ${TOKEN}, code=" + code + ", error" + error)
                agoraLogin = code == 200
                if(code==200){
                    onConfirm?.invoke(true)
                }else{
                    CoroutineScope(Dispatchers.Main).launch {
                        delay(1000)
                        loginToAgora(USERNAME, TOKEN)
                    }
                   // UtilsApp.getTopActivity().showToast(error)
                    onConfirm?.invoke(false)
                }
            }
        })
    }



    fun signOut() {
        if (ChatClient.getInstance().isLoggedInBefore) {
            ChatClient.getInstance().logout(true, object : CallBack {
                override fun onSuccess() {
                    agoraLogin = false
                }

                override fun onError(code: Int, error: String) {
                }
            })
        } else {
        }
    }

    fun getMessageList(): Map<String, Conversation> {

        return ChatClient.getInstance().chatManager().allConversations
    }
    //未打通
    fun sendImCallMsg(uid: String) {
        val customMessage = ChatMessage.createSendMessage(ChatMessage.Type.CUSTOM)
        val event = EVENT_TYPING_CALL
        val customBody = CustomMessageBody(event)
        val callMessageMap = CallMessage().toMap()
        customBody.params = callMessageMap
        customMessage.addBody(customBody)
        customMessage.to = uid
        customMessage.chatType = ChatMessage.ChatType.Chat
        // 发送消息。
        customMessage.setMessageStatusCallback(object : CallBack {
            override fun onSuccess() { //showToast("发送消息成功");
                Log.e("chat","发送消息成功")
            }

            override fun onError(code: Int, error: String) { //showToast("发送消息失败");
                Log.e("chat",error+"code="+code)
            }
        })
        ChatClient.getInstance().chatManager().sendMessage(customMessage)
    }
    private var lastCallTime = 0L
    //打通
    fun sendImCallMsg(uid: String,callMessage:CallMessage) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastCallTime < 1000) {
            // 如果距离上次调用不到1秒，直接返回
            return
        }
        // 更新最后调用时间
        lastCallTime = currentTime
        val customMessage = ChatMessage.createSendMessage(ChatMessage.Type.CUSTOM)
        val event = AgoraClient.EVENT_TYPING_CALL
        val customBody = CustomMessageBody(event)

        val callMessageMap = callMessage.toMap()
        customBody.params = callMessageMap
        customMessage.addBody(customBody)
        customMessage.to = uid.toString()
        customMessage.chatType = ChatMessage.ChatType.Chat
        // 发送消息。
        ChatClient.getInstance().chatManager().sendMessage(customMessage)
    }
    fun sendImGiftMsg(uid :String,gift : GiftInfo):ChatMessage{
        val customMessage = ChatMessage.createSendMessage(ChatMessage.Type.CUSTOM)
        val event = AgoraClient.EVENT_TYPING_GIFT
        val customBody = CustomMessageBody(event)
        val giftMessage = GiftMessage(gift.giftIcon, gift.giftUrl, gift.giftName)
        val giftMessageMap = giftMessage.toMap()
        customBody.params = giftMessageMap
        customMessage.addBody(customBody)
        customMessage.to = uid
        customMessage.chatType = ChatMessage.ChatType.Chat
        customMessage.setMessageStatusCallback(object : CallBack {
            override fun onSuccess() {

            }

            override fun onError(code: Int, error: String) {
                Log.e("tag", error)
            }
        }) // 发送消息。
        ChatClient.getInstance().chatManager().sendMessage(customMessage)
        return customMessage

    }
}
